<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>小组图片展示与点赞平台</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <!-- 引入 Supabase 作为后端服务 -->
  <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>

  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#4F46E5',
            secondary: '#10B981',
          },
        }
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .image-card {
        @apply bg-white rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-all duration-300 border border-gray-100;
      }
      .like-btn {
        @apply flex items-center justify-center space-x-1 bg-gray-100 hover:bg-gray-200 p-2 rounded-md transition-colors;
      }
      .liked {
        @apply bg-red-100 text-red-600;
      }
    }
  </style>
</head>

<body class="bg-gray-50 min-h-screen">
  <div class="container mx-auto px-4 py-8 max-w-6xl">
    <!-- 标题区域 -->
    <header class="text-center mb-8">
      <h1 class="text-3xl font-bold text-gray-800">小组图片展示与点赞平台</h1>
      <p class="text-gray-600 mt-2">10组学生上传图片，师生共同点赞互动</p>

      <div class="mt-4 flex flex-col md:flex-row items-center justify-center gap-4">
        <!-- 小组选择 -->
        <div class="flex items-center bg-white px-3 py-2 rounded-md shadow-sm border border-gray-200">
          <label for="group-select" class="text-sm text-gray-600 mr-2">选择小组：</label>
          <select id="group-select" class="border-none focus:ring-0 text-gray-800">
            <option value="1">第1组</option>
            <option value="2">第2组</option>
            <option value="3">第3组</option>
            <option value="4">第4组</option>
            <option value="5">第5组</option>
            <option value="6">第6组</option>
            <option value="7">第7组</option>
            <option value="8">第8组</option>
            <option value="9">第9组</option>
            <option value="10">第10组</option>
          </select>
        </div>

        <!-- 登录状态 -->
        <div id="auth-status" class="flex items-center text-sm px-3 py-2 rounded-full bg-gray-100 text-gray-800">
          <i class="fa fa-user-circle mr-2"></i>
          <span>游客模式</span>
          <button id="login-btn" class="ml-2 text-primary hover:text-primary/80 text-sm font-medium">登录</button>
        </div>
      </div>
    </header>

    <!-- 上传区域 -->
    <div class="bg-white p-6 rounded-lg shadow-sm mb-8">
      <h2 class="text-xl font-semibold text-gray-800 mb-4">本小组上传</h2>
      <div class="flex flex-col md:flex-row items-center gap-4">
        <div class="flex-1">
          <input type="file" id="image-upload" accept="image/*" class="hidden" onchange="handleImageUpload(event)">
          <label for="image-upload" class="inline-flex items-center bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-md cursor-pointer transition-colors">
            <i class="fa fa-upload mr-2"></i>选择图片上传
          </label>
          <p class="text-sm text-gray-500 mt-2">支持JPG、PNG格式，最大5MB</p>
        </div>
        <div id="local-preview" class="w-full md:w-64 h-40 bg-gray-100 rounded-md flex items-center justify-center overflow-hidden">
          <i class="fa fa-picture-o text-gray-400 text-4xl"></i>
        </div>
      </div>
    </div>

    <!-- 所有小组图片展示区 -->
    <div>
      <h2 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
        <i class="fa fa-th-large text-primary mr-2"></i>所有小组上传的图片
      </h2>
      <div id="all-images-container" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
        <!-- 图片将动态加载到这里 -->
        <div class="col-span-full text-center py-12 text-gray-500">
          <i class="fa fa-cloud-upload text-5xl mb-3 opacity-30"></i>
          <p>等待各小组上传图片...</p>
        </div>
      </div>
    </div>
  </div>

  <!-- 登录模态框 -->
  <div id="login-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
      <h3 class="text-xl font-semibold text-gray-800 mb-4">登录</h3>
      <div class="space-y-4">
        <div>
          <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
          <input type="text" id="username" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="请输入用户名">
        </div>
        <div>
          <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
          <input type="password" id="password" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="请输入密码">
        </div>
        <div class="flex justify-end">
          <button id="confirm-login" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">登录</button>
          <button id="cancel-login" class="ml-2 px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition-colors">取消</button>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 初始化 Supabase（使用公开测试项目）
    const supabaseUrl = 'https://qfdyueuqxzxnzwtzmwjj.supabase.co';
    const supabaseKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFmZHl1ZXVxeHp4bnp3dHptd2pqIiwicm9sZSI6ImFub24iLCJpYXQiOjE2ODc3OTQ1NzUsImV4cCI6MjAwMzM3MDU3NX0.QJQd8cH3rRqJ2XlGQJZ7JQJZ7JQJZ7JQJZ7JQJZ7JQ';
    const supabase = window.supabase.createClient(supabaseUrl, supabaseKey);

    // 存储所有小组的图片数据和点赞数
    let groupData = {};
    // 当前选择的小组
    let currentGroup = 1;
    // 当前登录用户
    let currentUser = null;

    // DOM 元素
    const groupSelect = document.getElementById('group-select');
    const localPreview = document.getElementById('local-preview');
    const allImagesContainer = document.getElementById('all-images-container');
    const loginBtn = document.getElementById('login-btn');
    const authStatus = document.getElementById('auth-status');
    const loginModal = document.getElementById('login-modal');
    const confirmLogin = document.getElementById('confirm-login');
    const cancelLogin = document.getElementById('cancel-login');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');

    // 初始化
    async function init() {
      // 监听小组选择变化
      groupSelect.addEventListener('change', (e) => {
        currentGroup = parseInt(e.target.value);
        updateLocalPreview();
      });

      // 监听登录按钮
      loginBtn.addEventListener('click', () => {
        loginModal.classList.remove('hidden');
      });

      // 监听取消登录
      cancelLogin.addEventListener('click', () => {
        loginModal.classList.add('hidden');
      });

      // 监听确认登录
      confirmLogin.addEventListener('click', async () => {
        const username = usernameInput.value.trim();
        const password = passwordInput.value.trim();

        if (!username || !password) {
          alert('请输入用户名和密码');
          return;
        }

        // 这里简化处理，实际项目可结合 Supabase 认证
        currentUser = { username };
        updateAuthStatus();
        loginModal.classList.add('hidden');
        usernameInput.value = '';
        passwordInput.value = '';
      });

      try {
        // 获取已有图片和点赞数据
        const { data: imagesData, error: imagesError } = await supabase
          .from('group_images')
          .select('*');

        const { data: likesData, error: likesError } = await supabase
          .from('likes')
          .select('*');

        if (imagesError || likesError) throw new Error(imagesError?.message || likesError?.message);

        // 处理图片数据
        if (imagesData && imagesData.length > 0) {
          imagesData.forEach(item => {
            groupData[item.group_id] = {
              url: item.image_url,
              timestamp: item.created_at,
              likes: 0
            };
          });
        }

        // 处理点赞数据
        if (likesData && likesData.length > 0) {
          likesData.forEach(like => {
            if (groupData[like.group_id]) {
              groupData[like.group_id].likes += 1;
            }
          });
        }

        renderAllImages();
        updateLocalPreview();

        // 监听图片变化
        const imageSubscription = supabase
          .channel('image-changes')
          .on(
            'postgres_changes',
            { event: '*', schema: 'public', table: 'group_images' },
            (payload) => {
              handleImageChange(payload);
            }
          )
          .subscribe();

        // 监听点赞变化
        const likeSubscription = supabase
          .channel('like-changes')
          .on(
            'postgres_changes',
            { event: '*', schema: 'public', table: 'likes' },
            (payload) => {
              handleLikeChange(payload);
            }
          )
          .subscribe();

      } catch (error) {
        console.error('初始化失败:', error);
        alert('加载数据失败，请刷新页面重试');
      }
    }

    // 处理图片变化
    function handleImageChange(payload) {
      if (payload.eventType === 'INSERT' || payload.eventType === 'UPDATE') {
        const newData = payload.new;
        groupData[newData.group_id] = {
          url: newData.image_url,
          timestamp: newData.created_at,
          likes: groupData[newData.group_id]?.likes || 0
        };
      } else if (payload.eventType === 'DELETE') {
        delete groupData[payload.old.group_id];
      }
      renderAllImages();
      updateLocalPreview();
    }

    // 处理点赞变化
    function handleLikeChange(payload) {
      if (payload.eventType === 'INSERT') {
        if (groupData[payload.new.group_id]) {
          groupData[payload.new.group_id].likes += 1;
        }
      } else if (payload.eventType === 'DELETE') {
        if (groupData[payload.old.group_id]) {
          groupData[payload.old.group_id].likes -= 1;
        }
      }
      renderAllImages();
    }

    // 处理图片上传
    async function handleImageUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      // 检查文件大小
      if (file.size > 5 * 1024 * 1024) {
        alert('图片大小不能超过5MB');
        return;
      }

      // 读取并压缩图片
      const compressedDataUrl = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = function (e) {
          compressImage(e.target.result, 800, 600, resolve);
        };
        reader.readAsDataURL(file);
      });

      try {
        // 保存到数据库
        const { error } = await supabase
          .from('group_images')
          .upsert([
            {
              group_id: currentGroup,
              image_url: compressedDataUrl,
              created_at: new Date()
            }
          ]);

        if (error) throw error;

        // 更新本地预览
        showLocalPreview(compressedDataUrl);

        alert('图片上传成功');

      } catch (error) {
        console.error('上传失败:', error);
        alert('上传失败，请重试');
      } finally {
        // 重置上传控件
        event.target.value = '';
      }
    }

    // 显示本地预览
    function showLocalPreview(imageUrl) {
      localPreview.innerHTML = `<img src="${imageUrl}" class="w-full h-full object-cover" alt="预览图">`;
    }

    // 重置本地预览
    function resetLocalPreview() {
      localPreview.innerHTML = '<i class="fa fa-picture-o text-gray-400 text-4xl"></i>';
    }

    // 更新本地预览
    function updateLocalPreview() {
      if (groupData[currentGroup] && groupData[currentGroup].url) {
        showLocalPreview(groupData[currentGroup].url);
      } else {
        resetLocalPreview();
      }
    }

    // 渲染所有图片
    function renderAllImages() {
      // 如果没有图片
      if (Object.keys(groupData).length === 0) {
        allImagesContainer.innerHTML = `
          <div class="col-span-full text-center py-12 text-gray-500">
            <i class="fa fa-cloud-upload text-5xl mb-3 opacity-30"></i>
            <p>等待各小组上传图片...</p>
          </div>
        `;
        return;
      }

      // 生成图片网格
      allImagesContainer.innerHTML = '';

      // 为10个小组都创建容器
      for (let i = 1; i <= 10; i++) {
        const imageCard = document.createElement('div');
        imageCard.className = 'image-card';

        if (groupData[i] && groupData[i].url) {
          // 已上传图片
          imageCard.innerHTML = `
            <div class="h-48 overflow-hidden">
              <img src="${groupData[i].url}" class="w-full h-full object-cover transition-transform hover:scale-110 duration-500" 
                   alt="第${i}组的图片">
            </div>
            <div class="p-3">
              <div class="flex justify-between items-center">
                <h3 class="font-medium text-gray-800">第${i}组</h3>
                <div class="like-btn" data-group="${i}">
                  <i class="fa fa-thumbs-up"></i>
                  <span>${groupData[i].likes || 0}</span>
                </div>
              </div>
              <p class="text-xs text-gray-500 mt-1">
                ${formatTime(groupData[i].timestamp)}
              </p>
            </div>
          `;

          // 绑定点赞事件
          const likeBtn = imageCard.querySelector('.like-btn');
          likeBtn.addEventListener('click', async () => {
            if (!currentUser) {